# coding=utf-8
from sqlalchemy.exc import IntegrityError

from common.lottery.cyclical.abstract import activity as base
from common.utils.decorator import sql_wrapper
from common.lottery.cyclical.model import ACTIVITY_MODEL


@sql_wrapper
def insert_stats(lottery_type, term, number, last_stats):
    trend, save = base.generate_trend(
        lottery_type, term, number, last_stats)

    trend, save = calc_miss(last_stats, number, save, trend)

    if save:
        repeat_numbers = len(set(trend.number.split(',')) & set(last_stats.number.split(',')))
        activity_model = ACTIVITY_MODEL[lottery_type]
        ac = activity_model.query.filter(activity_model.term == term).first()
        if ac:
            ac.repeat_numbers = repeat_numbers
            ac.save()

        try:
            trend.repeat_numbers = repeat_numbers
            trend.save()
        except IntegrityError:
            pass
    return trend


def calc_miss(last_stats, number, save, trend):
    def calc_func(last, i):
        return str(int(last[i]) + 1) if last[i] != 'x' else 'x'

    number = number.split(',')
    # 任选二到八
    last = last_stats.miss_1.split(',')
    for i in xrange(len(last)):
        last[i] = calc_func(last, i)
    for n in number:
        last[int(n) - 1] = '0'
    if 'x' in last:
        save = False
    trend.miss_1 = ','.join(last)
    # 前二组选
    last = last_stats.miss_10.split(',')
    for i in xrange(len(last)):
        last[i] = calc_func(last, i)
    for n in number[:2]:
        last[int(n) - 1] = '0'
    if 'x' in last:
        save = False
    trend.miss_10 = ','.join(last)
    # 前三组选
    last = last_stats.miss_12.split(',')
    for i in xrange(len(last)):
        last[i] = calc_func(last, i)
    for n in number[:3]:
        last[int(n) - 1] = '0'
    if 'x' in last:
        save = False
    trend.miss_12 = ','.join(last)

    return trend, save
